# -- coding:utf-8 --
import os
from openpyxl import Workbook
import investor


# class Senti(object)
def senti_day_addr(path):
    d = {}
    for dir in os.listdir(path):
        day = dir
        _p = os.path.join(path, dir)
        if os.path.isdir(_p):
            lst = list_dir(_p)
            for line in lst:
                guba = investor.Guba.fromString(line.strip("\n"))
                addr = guba.news.address
                neg = int(guba.senti.neg)
                pos = int(guba.senti.pos)
                k = "%s:%s" % (day,addr)
                if k in d:
                    _day,_addr,_neg,_pos = d[k]
                    d[k] = (_day,_addr,_neg+neg, _pos+pos)
                else:
                    d[k] = (day, addr, neg, pos)
                # print(guba)
    lines = []
    for v in d.values():
        lines.append("\t".join(map(str,v))+"\n")
        _p = os.path.join(path,"按来源")
    save_xls(_p, lines)


def list_dir(path):
    lst = []
    for _p in os.listdir(path):
        with open(os.path.join(path, _p), "r") as f:
            lines = f.readlines()
            if lines:
                lst.extend(lines)
    return lst


def split_lst(lst, path):
    guba_d = {}
    for line in lst:
        guba = investor.Guba.fromString(line.strip("\n"))
        key = "%s:%s:%s" % (guba.secu.code, guba.secu.name, guba.news.time[:10])
        if not key in guba_d:
            guba_d[key] = []
        guba_day_lst = guba_d.get(key)
        guba_day_lst.append(guba)

    for k, v in guba_d.items():
        code, name, day = k.split(":")
        guba_lst = dist_guba(v)

        _path = os.path.join(path, day)
        file = "%s_%s.txt" % (code, name)
        save_txt(_path, file, guba_lst)


def dist_guba(guba_lst):
    url_set = set([])
    ret_lst = []
    for guba in guba_lst:
        if not guba.url in url_set:
            url_set.add(guba.url)
            ret_lst.append(str(guba) + '\n')
    return ret_lst


def save_txt(path, file, lst):
    if not os.path.exists(path):
        os.makedirs(path)
    with open("%s/%s" % (path, file), "w") as f:
        f.writelines(lst)


def cat_txt(path):
    lst = [investor.Guba.head() + "\n"]
    for _p in os.listdir(path):
        with open(os.path.join(path, _p), "r") as f:
            lines = f.readlines()
            if lines:
                lst.extend(lines)

    if lst:
        save_xls(path, lst)


def merge():
    lst = []
    lst.extend(list_dir("20240224"))
    lst.extend(list_dir("20240225"))
    split_lst(lst, path="result")


def save_xls(path, lines):
    # 创建一个新的工作簿
    workbook = Workbook()

    # 获取活动工作表
    sheet = workbook.active

    # 写入多行数据
    data = []
    for line in lines:
        line = line.strip("\n")
        data.append(line.split("\t"))

    for row in data:
        sheet.append(row)

    # 保存工作簿
    workbook.save(filename='%s_沪深300_股吧.xlsx' % path)

def list_day(path):
    from datetime import datetime, timedelta

    # 开始日期
    start_date = datetime(2023, 1, 1)

    # 创建一个空的日期数组
    date_array = []

    # 生成365天的日期
    for i in range(365):
        # 将日期转换为字符串并添加到数组中
        date_str = start_date.strftime("%Y-%m-%d")
        date_array.append(date_str)
        # 递增日期
        start_date += timedelta(days=1)


    d_day = set()
    with open(path,"r") as f:
        lst = f.readlines()
        for line in lst:
            guba = investor.Guba.fromString(line.strip("\n"))
            day = guba.news.time[:10]
            d_day.add(day)

    lst = list((set(date_array) - d_day))
    lst.sort()
    lines = [ "%s\n" % d for d in lst]
    with open("miss_day.txt", "w") as f:
        f.writelines(lines)

if __name__ == "__main__":
    cat_txt("result/2023")
    # merge()
    # senti_day_addr("result")
    # list_day("result/2023/zssh000001_上证指数.txt")
